﻿using InfonavaEye.common;
using InfonavaEye.components;
using InfonavaEye.model;
using InfonavaEye.model.wjapi;
using InfonavaEye.Service;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace InfonavaEye.Forms.orderForms
{
    public partial class OrderIndex : Form
    {

        private string orderNo = "";
        private int checkSubmitBtnModel = 0;
        private BoxModel boxModel;
        static Dictionary<int, ConfirmCheckResultParam> paramDict = new System.Collections.Generic.Dictionary<int, ConfirmCheckResultParam>();
        private List<IE1ItemResultDto> itemData;
        public OrderIndex()
        {
            InitializeComponent();
        }
        private void MainForm_Load(object sender, EventArgs e)
        {
            paramDict.Clear();
            this.orderListView.orderViewChangeDelegate += OrderListView_changeDelegateDelegate;

        }
        //this.orderDataView.Rows.Clear();
        private void OrderListView_changeDelegateDelegate(string eventCode,string orderNo)
        {
            if("selectd".Equals(eventCode)) {
                this.orderNo = orderNo;
                this.checkSubmitBtn.Enabled = true;
                return; 
            }
            if ("updateBtnStatu".Equals(eventCode)) {
                this.orderNo = orderNo; 
                this.checkSubmitBtn.Text = "订单核验";
            }

        }

        private void orderCheck() {
            if (FormDataBridge.OCRDataList == null || FormDataBridge.OCRDataList.Count <= 0)
            {
                AutoCloseMessageBox.Show("没有可提交的数据");
                return;
            }
            if ("".Equals(orderNo)) {
                AutoCloseMessageBox.Show("未选择需要核验的单据");
                return;
            }
            paramDict.Clear();
            Task.Factory.StartNew(() =>
            {
                var service = ReportServiceFactory.getService();
                this.boxModel = this.boxModel == null ? new BoxModel() : boxModel;
                CheckResult checkResult = service.checkOrder<CheckResult>(new ReportDTO()
                {
                    BoxModel = this.boxModel,
                    OcrResults = FormDataBridge.OCRDataList
                }, orderNo);
                if (checkResult == null)
                {
                    return;
                }
                this.checkSubmitBtn.Visible = true;
                this.closeBtn.Visible = true;
               
                itemData = checkResult.itemData;
                DataGridViewRow[] rows = new DataGridViewRow[itemData.Count];
                int i = 0;
                foreach (IE1ItemResultDto result in itemData)
                {
                    string comparisonTxt = "-";
                    if (result.orderQuantity == result.itemQuantity)
                    {
                        comparisonTxt = "正常";
                    }
                    if (result.orderQuantity > result.itemQuantity)
                    {
                        comparisonTxt = "少";
                    }
                    if (result.orderQuantity < result.itemQuantity)
                    {
                        comparisonTxt = "多";
                    }
                    result.comparisonTxt = comparisonTxt;
                }
                this.orderDataView.AutoGenerateColumns = false;
                this.orderDataView.Columns[1].Visible = false;
                this.orderDataView.Columns[2].Visible = false;
                this.orderDataView.Columns[3].Visible = false;
                this.Invoke(new Action(delegate {
                    this.orderDataView.Rows.Clear();
                    this.showOrderDataView();
                    // 绑定数据源
                    this.orderDataView.DataSource = new BindingSource(new BindingList<IE1ItemResultDto>(itemData), null);
                   
                    readerRowBgColor(itemData);
                }));
                //this.orderDataView.FirstDisplayedScrollingRowIndex = ((int)ScrollOrientation.VerticalScroll);

            });

        }
        private void showOrderDataView() {
            this.orderListView.Visible = false;
            this.orderDataView.Visible = true;
            this.orderCheckReusltPanel.Visible = true;
            this.panel1.Visible = true;
            this.orderNOLabel.Text = "单号:" + this.orderNo;
            this.checkSubmitBtn.Enabled = true;
            this.checkSubmitBtn.Text = "确认提交";
            this.checkSubmitBtnModel = 1;
        }

        private void BackLabel_Click(object sender, System.EventArgs e)
        {
            this.orderListView.Visible = true;
            this.orderDataView.Visible = false;
            this.orderCheckReusltPanel.Visible = false;
            this.panel1.Visible = false;
            this.orderNOLabel.Text = "";
            this.checkSubmitBtn.Enabled = true;
            this.checkSubmitBtn.Text = "订单核验";
            this.checkSubmitBtnModel = 0;
        }

        private void readerRowBgColor(List<IE1ItemResultDto> itemData)
        {
            this.orderDataView.ClearSelection();
            for (int i = 0; i < itemData.Count; i++) {
                var rowData=itemData[i];
                if (rowData.orderQuantity != rowData.itemQuantity)
                {
                    this.orderDataView.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(241)))), ((int)(((byte)(182)))), ((int)(((byte)(182)))));
                }
            }
        }


        private void closeBtn_Click(object sender, EventArgs e)
        {
            paramDict.Clear();
            this.Close();
        }

        private void checkSubmitBtn_Click(object sender, EventArgs e)
        {
            if (this.checkSubmitBtnModel==0) {
                this.orderCheck();
                return;
            }
            if (this.checkSubmitBtnModel == 1)
            {
                this.SubmitCheckResul();
                return;
            }
        }
        private void SubmitCheckResul() {
            var viewDataRows = this.orderDataView.Rows;
            if (viewDataRows.Count <= 0)
            {
                AutoCloseMessageBox.Show("没有可提交的数据");
                return;
            }
            List<ConfirmCheckResultParam> paramList = new List<ConfirmCheckResultParam>();

            foreach (int rowIndex in paramDict.Keys) {
                ConfirmCheckResultParam param = paramDict[rowIndex];
                param.quantity = this.orderDataView.Rows[rowIndex].Cells[11].Value.ToString();
                if (param.quantity == null || "".Equals(param.quantity) )
                {
                    param.quantity = "0";
                }
                paramList.Add(param);
            }
          /*  foreach (ConfirmCheckResultParam v in paramDict.Values)
            {
                paramList.Add(v);
            }*/
            if (paramList.Count <= 0)
            {
                AutoCloseMessageBox.Show("请选择要提交的数据");
                return;
            }

            Task.Factory.StartNew(() =>
            {
                this.checkSubmitBtn.Enabled = false;
                this.checkSubmitBtn.Text = "提交中...";
                var service = ReportServiceFactory.getService();
                Boolean result = service.submitCheckReceiptResult(new SubmitCheckDataDTO()
                {
                    OrderNO = this.orderNo,
                    paramList = paramList
                });
                if (result)
                {
                    AutoCloseMessageBox.Show("提交成功");
                    this.Close();
                }
                else
                {
                    this.checkSubmitBtn.Text = "确认无误";
                    this.checkSubmitBtn.Enabled = true;
                }

            });
        }

        private void orderDataView_CellClick(object sender, DataGridViewCellEventArgs e) {


            if (e.ColumnIndex != 0)
            {
                return;
            }
            //    点击的是标题栏--全选
            bool isAllSelectd = false;
            if (e.RowIndex == -1 && e.ColumnIndex == 0)
            {
                isAllSelectd = true;
            }

            for (int i = 0; i < orderDataView.Rows.Count; i++)
            {
                if (isAllSelectd||e.RowIndex == i)
                {
                    this.orderDataView.Rows[i].Selected = !this.orderDataView.Rows[i].Selected;
                    DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)orderDataView.Rows[i].Cells[0];
                    Boolean flag = Convert.ToBoolean(checkCell.Value);
                    checkCell.Value = !flag;
                    rowsSelectEvent(i, !flag);
                }
            }
        }
   

        private void rowsSelectEvent(int rowIndex,Boolean selectd) {
            if (paramDict.ContainsKey(rowIndex)) {
                paramDict.Remove(rowIndex);
            }
            if (selectd) {
                ConfirmCheckResultParam param = new ConfirmCheckResultParam();
                param.itemCode = this.orderDataView.Rows[rowIndex].Cells[1].Value.ToString();
                param.batchNumber = this.orderDataView.Rows[rowIndex].Cells[2].Value.ToString();
                param.lineNumber = this.orderDataView.Rows[rowIndex].Cells[3].Value.ToString();
                param.quantity = this.orderDataView.Rows[rowIndex].Cells[11].Value.ToString();
                if (param.quantity == null || "".Equals(param.quantity) )
                {
                    param.quantity = "0";
                }
                paramDict.Add(rowIndex, param);
            }
        }

      
        private void orderDataView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            this.orderDataView.Rows[e.RowIndex].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleLeft;
            this.orderDataView.Rows[e.RowIndex].HeaderCell.Value = "+";
        }

        private void orderDataView_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            this.orderDataView.CurrentRow.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleLeft;
            this.orderDataView.CurrentRow.HeaderCell.Value = Convert.ToString(this.orderDataView.CurrentRow.HeaderCell.Value).Trim() == "+" ? "-" : "+"; 
            int scrollRowIndex = this.orderDataView.FirstDisplayedScrollingRowIndex;  
            if ((e.RowIndex - scrollRowIndex) > 10)  
            {
                this.orderDataView.FirstDisplayedScrollingRowIndex = e.RowIndex;
            }
            System.Drawing.Rectangle rect = this.orderDataView.GetCellDisplayRectangle(-1, e.RowIndex, false);
            this.laserCodeDataView.Left = rect.Left;
            this.laserCodeDataView.Top = rect.Bottom;
            this.laserCodeDataView.Width = 800;//this.orderDataView.Width;
            this.laserCodeDataView.Height = 400; //this.orderDataView.Height;
            renderLaserCodeDataView(e.RowIndex);
            this.laserCodeDataView.Visible = Convert.ToString(this.orderDataView.CurrentRow.HeaderCell.Value).Trim() == "-" ? true : false;  
        }
        private void renderLaserCodeDataView(int rowIndex) {
            var rowData = itemData[rowIndex];
            this.laserCodeDataView.DataSource = rowData.laserCode;
        }
        private void laserCodeDataView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            try
            {
                //添加行号 
                SolidBrush v_SolidBrush = new SolidBrush(this.laserCodeDataView.RowHeadersDefaultCellStyle.ForeColor);
                int v_LineNo = 0;
                v_LineNo = e.RowIndex + 1;
                string v_Line = v_LineNo.ToString();
                e.Graphics.DrawString(v_Line, e.InheritedRowStyle.Font, v_SolidBrush, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + 5);

            }
            catch (Exception ex)
            {
                Console.WriteLine("添加行号时发生错误，错误信息：" + ex.Message, "操作失败");
            }
        }

        private void orderDataView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) {
            try
            {
                //添加行号 
                SolidBrush v_SolidBrush = new SolidBrush(this.orderDataView.RowHeadersDefaultCellStyle.ForeColor);
                int v_LineNo = 0;
                v_LineNo = e.RowIndex + 1;
                string v_Line = v_LineNo.ToString();
                e.Graphics.DrawString(v_Line, e.InheritedRowStyle.Font, v_SolidBrush, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + 5);

            }
            catch (Exception ex)
            {
                Console.WriteLine("添加行号时发生错误，错误信息：" + ex.Message, "操作失败");
            }

        }
    }

}
